<template>
  <div class="p-2 erpNativeList">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter="reload" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
  <div class="content">
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'customers_pool:customers_pool:add'"  @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button type="primary" v-auth="'customers_pool:customers_pool:exportXls'"  preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary"  v-auth="'customers_pool:customers_pool:importExcel'" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button  v-auth="'customers_pool:customers_pool:deleteBatch'"
            >批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
        <!-- 第三方API按钮 -->
        <a-button type="primary" @click="handleThirdPartyApi" preIcon="ant-design:team-outlined"> 第三方API导入</a-button>
                 <!-- 确认需求按钮 -->
         <a-button type="primary" @click="handleConfirmRequirement" :disabled="!selectedRow " style="margin-left: 8px" preIcon="ant-design:check-circle-outlined"> 确认需求</a-button>
         <!-- 商机认领按钮 -->
         <a-button type="primary" @click="handleBusinessAssign" :disabled="!selectedRow " style="margin-left: 8px" preIcon="ant-design:user-add-outlined"> 商机认领</a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <!--（如需自定义显示可在此插槽实现）-->
    </BasicTable>
    <!--子表表格tab-->
    <a-tabs defaultActiveKey="1" style="margin: 10px">
      <a-tab-pane tab="客户联系人信息" key="1" >
        <ContactsList ref="contactsListRef" />
      </a-tab-pane>
      <a-tab-pane tab="需求确认人员" key="2" forceRender>
        <CustomerPrincipalList ref="principalListRef" @refreshMain="reload" />
      </a-tab-pane>

     </a-tabs>
  </div>
    <!-- 表单区域 -->
    <CustomersPoolModal ref="registerModal" @success="handleSuccess" />

    <!-- 商务人员分配模态框 -->
    <BusinessAssignModal ref="businessAssignModalRef" @ok="handleBusinessAssignOk" />
  </div>
</template>

<script lang="ts" name="customers_pool-customersPool" setup>
  import { ref, reactive, computed, unref, provide } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage'
  import CustomersPoolModal from './components/CustomersPoolModal.vue'
  import TaskAllocationModal from './components/TaskAllocationModal.vue'
import BusinessAssignModal from './components/BusinessAssignModal.vue'
  import { columns, superQuerySchema } from './CustomersPool.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, taskList, task2sysUser, saveOrUpdate, assignBusinessDeptUser } from './CustomersPool.api';
  import ContactsList from './ContactsList.vue'
  import CustomerPrincipalList from './CustomerPrincipalList.vue'
  import RequirementPersonList from './RequirementPersonList.vue'
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { func } from 'vue-types';


  import {searchFormSchema} from "@/views/system/position/position.data";
import { message, Modal } from 'ant-design-vue';
import { h } from 'vue';
  const formRef = ref();
  const queryParam = reactive<any>({});
  const registerModal = ref();
  const contactsListRef = ref();
  const principalListRef = ref();
  const requirementPersonListRef = ref();
  const taskModalRef = ref();
  const businessAssignModalRef = ref();
  const { createMessage } = useMessage();
  const userStore = useUserStore(); // 获取用户信息
   //注册table数据
  const { tableContext,onExportXls,onImportXls } = useListPage({
    tableProps:{
      title: '客户表',
      api: list,
      columns,
      canResize:false,
      useSearchForm: false,
      clickToRowSelect: true,
      rowSelection: {type: 'checkbox'},
      actionColumn: {
        width: 180,
        fixed:'right'
      },
      formConfig: {
        schemas: searchFormSchema,
      },
      showIndexColumn: true,
      beforeFetch: async (params) => {
        return Object.assign(params, queryParam);
      },
      pagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20'],
      },
    },
    exportConfig: {
      name:"客户表",
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  })

  const [registerTable, { reload, getDataSource },{ rowSelection, selectedRowKeys }] = tableContext
  const mainId = computed(() => (unref(selectedRowKeys).length === 1 ? unref(selectedRowKeys)[0] : ''));
  const customerId = computed(() => (unref(selectedRowKeys).length === 1 ? unref(selectedRowKeys)[0] : ''));
  //下发 mainId,子组件接收
  provide('mainId', mainId);
  provide('customerId', customerId);
  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  const selectedRow = computed(() => {
    if (unref(selectedRowKeys).length > 0) {
      return getDataSource().find(item => item.id === unref(selectedRowKeys)[0]);
    }
    return null;
  });





  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    // 自动填充当前登录用户真实姓名到 createBy 字段
    const realName = userStore.getUserInfo.realname;
    registerModal.value.add({ createBy: realName });
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
     registerModal.value.disableSubmit = false;
     registerModal.value.edit(record);
  }

  /**
   * 详情事件
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({id: record.id}, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ids: selectedRowKeys.value},handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  function handleThirdPartyApi() {
    createMessage.warning('第三方API导入功能尚未实现');
  }

  /**
   * 商机认领处理
   */
  function handleBusinessAssign() {
    // 检查是否有选中的行
    if (!selectedRow.value || !selectedRow.value.id) {
      createMessage.warning('请先选择一个客户');
      return;
    }
    
    // 打开商务人员分配模态框
    businessAssignModalRef.value.open(selectedRow.value);
  }

  /**
   * 商务人员分配确认回调
   */
  async function handleBusinessAssignOk(businessUser) {
    try {
      const record = businessAssignModalRef.value.currentRecord;
      // 检查客户ID是否存在
      if (!record.id) {
        createMessage.error('客户ID不存在');
        businessAssignModalRef.value.resetConfirmLoading(); // 重置按钮状态
        return;
      }

      console.log('商务人员分配参数:', {
        customerId: record.id,
        userId: businessUser.userId,
        developRole: '商务跟进人员'
      });

      // 1. 调用后端接口进行商务人员分配
      const assignParams = {
        id: record.id,
        userId: businessUser.userId,
        developRole: '商务跟进人员'
      };

             const res = await assignBusinessDeptUser(assignParams);
       console.log("res = ", res);

       // 根据后端返回结果判断是否成功
       if (res && res.success) {
         // 分配成功
         console.log('客户信息更新成功');
         createMessage.success('商务人员分配成功');
         // 关闭模态框
         businessAssignModalRef.value.visible = false;

         // 刷新列表数据
         reload();
         // 刷新子表数据
         principalListRef.value.reload();
       } else {
         // 分配失败
         const errorMsg = res?.message || '商务人员分配失败';
         createMessage.error(errorMsg);
         businessAssignModalRef.value.resetConfirmLoading(); // 重置按钮状态
       }
    } catch (error) {
      // 发生错误时重置按钮状态
      businessAssignModalRef.value.resetConfirmLoading();
      console.error('商务人员分配错误:', error);
      createMessage.error('商务人员分配失败: ' + ((error as any).message || '未知错误'));
    }
  }

  /**
   * 确认需求处理
   */
  async function handleConfirmRequirement() {
    try {
      // 检查是否有选中的行
      if (!selectedRow.value || !selectedRow.value.id) {
        createMessage.warning('请先选择一个客户');
        return;
      }

      // 获取当前登录用户ID
      const currentUserId = userStore.getUserInfo.id;
      if (!currentUserId) {
        createMessage.error('获取当前用户信息失败');
        return;
      }

      // 显示确认弹框
      const record = selectedRow.value;
      Modal.confirm({
        title: '确认客户有需求',
        content: h('div', [
          h('div', { style: 'margin-bottom: 16px; font-size: 14px; color: #666;' }, '您即将确认该客户有需求，请确认操作'),
          h('div', { style: 'background: #f5f5f5; padding: 12px; border-radius: 6px; border-left: 4px solid #1890ff;' }, [
            h('div', { style: 'font-weight: 500; margin-bottom: 8px; color: #333;' }, '选中客户信息：'),
            h('div', { style: 'color: #666; line-height: 1.6;' }, [
              h('div', `客户名称：${record.customerName || '暂无'}`),
              h('div', `客户编号：${record.customerCode || '暂无'}`),
              h('div', `分配状态：${record.status || '暂无'}`),
            ])
          ])
        ]),
        okText: '确认需求',
        cancelText: '取消',
        okType: 'primary',
        width: 480,
        centered: true,
        onOk: async () => {
          try {
            // 确认提示
            message.loading('正在处理需求确认...', 0);

            // 调用需求确认接口
            const params = {
              id: record.id,
              userId: currentUserId,
              developRole: '需求确认人员'
            };
            
            console.log('需求确认参数:', { id: record.id, userId: currentUserId, developRole: '需求确认人员' });
            const res = await assignBusinessDeptUser(params);
             
             // 关闭loading提示
             message.destroy();
             
             // 根据后端返回结果判断是否成功
             if (res && res.success) {
               createMessage.success('需求确认成功');

               // 刷新列表数据
               reload();
               // 刷新子表数据（需求信息表）
               principalListRef.value.reload();
             } else {
               // 需求确认失败
               const errorMsg = res?.message || '需求确认失败';
               createMessage.error(errorMsg);
             }
          } catch (error) {
            message.destroy();
            console.error('需求确认错误:', error);
            createMessage.error('需求确认失败: ' + ((error as any).message || '未知错误'));
          }
        }
      });
    } catch (error) {
      console.error('确认需求处理错误:', error);
      createMessage.error('确认需求处理失败: ' + ((error as any).message || '未知错误'));
    }
  }



  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'customers_pool:customers_pool:edit'
      },
    ];
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record){
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
             {
         label: '确认需求',
         onClick: () => {
           selectedRowKeys.value = [record.id];
           handleConfirmRequirement();
         },
       },
       {
         label: '商机认领',
         onClick: () => {
           selectedRowKeys.value = [record.id];
           handleBusinessAssign();
         },
       },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft'
        },
        auth: 'customers_pool:customers_pool:delete'
      },
    ];
  }


  /* ----------------------以下为原生查询需要添加的-------------------------- */
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }


</script>
<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
    .ant-form-item:not(.ant-form-item-with-help){
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),:deep(.ant-input-number){
      width: 100%;
    }
  }
  .erpNativeList {
      height: 100%;
      .content {
        background-color: #fff;
        height: 100%;
      }
  }
</style>
